package com.whale.mq.kafka;


import com.whale.mq.service.ConsumeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;




/**
 * Kafka消息接收
 */
@Component
@Slf4j
public class KafkaMqReceiver {

    @Autowired
    private ConsumeService consumeService;

    /**
     * 消息监听方法
     * @param record 接收到的Kafka消息记录
     * @param ack 确认接口，用于手动提交偏移量
     */
    @KafkaListener(topics = "order_topic")
    public void consumer(ConsumerRecord<String, String> record, Acknowledgment ack) {
        try {
            // 打印接收到的消息内容
            log.info("Received message: key={}, value={}", record.key(), record.value());
            // 调用业务服务处理接收到的消息
            consumeService.consumerKafka(record.value());
            // 手动提交偏移量
            ack.acknowledge();
        } catch (Exception e) {
            // 处理消息时发生异常，可以选择重新抛出异常让Spring自动进行失败处理
            log.error("Error processing message: key={}, value={}", record.key(), record.value(), e);
            // ack.ignore(); // 如果不想重新处理这条消息，可以选择忽略
            throw e;
        }
    }
}
